﻿using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace BToolkit.ExeUtils
{
    public class EditScale : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
    {
        RectTransform trans;
        bool isMouseOver;
        Vector3 oldScale;

        string SaveKey
        {
            get
            {
                string str = gameObject.name.Replace("(Clone)", "");
                if (transform.parent) str += "_" + transform.parent.name;
                return str;
            }
        }

        void OnDestroy()
        {
            MainController.onEditModeEnable -= OnEditModeEnable;
        }

        void Awake()
        {
            MainController.onEditModeEnable += OnEditModeEnable;
            trans = transform as RectTransform;
        }

        void Start()
        {
            if (DataStorage.GetFloat(SaveKey + "_Scale", 0) != 0)
            {
                trans.localScale = Vector3.one * DataStorage.GetFloat(SaveKey + "_Scale");
            }
        }

        public void OnPointerEnter(PointerEventData eventData)
        {
            if (!MainController.isEditMode) return;
            isMouseOver = true;
        }

        public void OnPointerExit(PointerEventData eventData)
        {
            isMouseOver = false;
        }

        void Update()
        {
            if (isMouseOver)
            {
                trans.localScale += Vector3.one * Input.mouseScrollDelta.y * Time.deltaTime;
            }
        }

        void OnEditModeEnable(bool b, bool save)
        {
            if (!b)
            {
                oldScale = transform.localScale;
                isMouseOver = false;
            }

            //取消控制
            BButton button = GetComponent<BButton>();
            if (button)
            {
                button.enabled = !b;
            }
            Dropdown dropdown = GetComponent<Dropdown>();
            if (dropdown)
            {
                dropdown.enabled = !b;
            }

            if (!b)
            {
                if (save)
                {
                    if (button) button.SetDefaultScale(trans.localScale);
                    DataStorage.SetFloat(SaveKey + "_Scale", trans.localScale.x);
                }
                else
                {
                    transform.localScale = oldScale;
                }
            }
        }
    }
}